<template>
  <div class="yoyo-container mx-auto min-h-screen pb-[env(safe-area-inset-bottom)]">
    <!-- 导航栏 -->
    <navBar :showBack="!$route.query.showTabbar">
      <div slot="title" class="flex-2 text-center">{{ $t("products.navTitle") }}（{{ cartItems.length }}）</div>
    </navBar>

    <div class="pt-2">
      <!-- 购物车商品列表 -->
      <div v-if="cartItems.length > 0">
        <div v-for="item in cartItems" :key="item.id" class="flex items-center p-3 bg-white mb-2 mx-4 rounded-lg">
          <div class="w-16 h-16 bg-blue-500 rounded-lg flex-shrink-0 mr-4"></div>

          <!-- 商品信息 -->
          <div class="flex-1">
            <h3 class="text-base font-medium mb-1">{{ item.region }}</h3>
            <div class="text-sm text-gray-500 mb-2">{{ item.selectedText }}</div>

            <!-- 价格和数量 -->
            <div class="flex items-center justify-between">
              <div class="flex items-center flex-row">
                <span class="text-xs text-gray-400 line-through">RM{{ formatToYuan(item.marketPrice) }}</span>
                <span class="ml-2 text-lg font-bold text-[#ff7a00]">RM {{ formatToYuan(item.price) }}</span>
              </div>

              <!-- 数量控制 -->
              <div class="flex items-center border border-gray-200 rounded px-2 py-1">
                <van-icon v-if="item.quantity === 1" name="delete" size="16" @click="removeItem(item.id)" />
                <van-icon v-else name="minus" size="16" color="black" @click="handleDecrease(item)" />
                <span class="mx-3 text-base">{{ item.quantity }}</span>
                <van-icon name="plus" size="16" :color="isMaxQuantityReached(item) ? '#ddd' : 'black'" @click="increaseQuantity(item)" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空购物车状态 -->
      <div v-else class="flex flex-col items-center justify-center mt-20">
        <van-empty :description="$t('products.cardEmpty')" />
      </div>
    </div>

    <!-- 优惠信息 -->
    <div v-if="cartItems.length > 0" class="mx-4 mt-4">
      <div class="bg-white rounded-lg p-3">
        <div class="space-y-2 text-sm">
          <div class="flex items-center">
            <span>{{ $t("products.cardDesc1") }}</span>
            <span class="text-[#ff7a00] font-medium">&nbsp;{{ $t("products.cardDesc4") }}</span>
          </div>
          <div class="flex items-center">
            <span>{{ $t("products.cardDesc2") }}</span>
          </div>
          <div class="flex items-center" v-if="!isLoggedIn">
            <span class="text-[#ff7a00]">{{ $t("products.cardDesc3") }}</span>
            <van-button type="primary" size="mini" plain class="ml-2 w-20" color="#ff7a00">{{ $t("products.cardBtnText1") }}</van-button>
          </div>
        </div>
      </div>
    </div>
    <div :class="[$route.query.showTabbar && showTabbar ? 'h-[calc(50px+6rem)] md:h-21' : 'h-21']"></div>
    <!-- 底部结算栏 -->
    <div
      v-if="cartItems.length > 0"
      :class="[
        'h-19 fixed bottom-0 left-0 right-0 pb-[env(safe-area-inset-bottom)] yoyo-container mx-auto',
        { 'bottom-[50px] md:bottom-0': $route.query.showTabbar & showTabbar },
      ]">
      <div class="flex h-full z-50 items-center pr-2 w-full lg:mx-4 lg:w-[calc(100%-2rem)] bg-white border-t border-gray-200 py-2">
        <div class="flex-1 text-right mr-4 flex flex-col justify-between">
          <div class="text-lg font-bold text-[#ff7a00]">RM {{ formatToYuan(totalAmount) }}</div>
          <div class="text-sm text-gray-500">
            {{ $t("products.cardDesc5") }}&nbsp;{{ formatToYuan(totalAmount) }} {{ $t("products.cardDesc6") }}，{{ $t("products.cardDesc7")
            }}{{ formatToYuan(totalAmount * 0.01) }}
          </div>
        </div>

        <!-- 结算按钮 -->
        <van-button type="primary" class="rounded-xl w-20 h-10" color="#ff7a00" :disabled="totalCount === 0" @click="checkout">
          {{ $t("products.cardBtnText2") }}
        </van-button>
      </div>
    </div>

    <van-tabbar  v-if="$route.query.showTabbar" route :class="['z-999 transition-transform duration-300 flex md:hidden', { 'translate-y-full': !showTabbar }]">
      <van-tabbar-item :to="item.to" v-for="item in tabbarItems" :key="item.name">
        <template #icon>
          <img :src="item.icon" class="w-14 h-14" />
        </template>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { Tabbar, TabbarItem } from "vant"
import { mapGetters, mapMutations } from "vuex"
import { formatToYuan } from "@/utils/common"
export default {
  name: "ShoppingCart",
  components: {
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
  },
  data() {
    return {
      backSrc: require("@/assets/images/back.png"),
      cartItems: [],
      maxQuantity: 2, // 最大可添加数量
      // tabbarItems: [
      //   { name: "cart", icon: require("@/assets/images/card.png"), to: { name: "cart", query: { showTabbar: true } }, w: 8 },
      //   { name: "home", icon: require("@/assets/images/home.png"), to: { name: "home" }, w: 8 },
      //   { name: "yoyoCoinIntroduce", icon: require("@/assets/images/yoyo.png"), to: { name: "yoyoCoinIntroduce" }, w: 10 },
      //   { name: "mine", icon: require("@/assets/images/mine.png"), to: { name: "mine" }, w: 10 },
      // ],
      activeTab: 0,
      formatToYuan,
       // 滚动相关状态
       showTabbar: true,
      lastScrollTop: 0,
      scrollThreshold: 1, // 滚动阈值
    }
  },
  computed: {
    totalCount() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0)
    },
    tabbarItems() {
      return this.isZh
        ? [
            { name: "home", icon: require("@/assets/images/tabbar/home.png"), to: { name: "home" }, w: 8 },
            { name: "yoyoCoinIntroduce", icon: require("@/assets/images/tabbar/yoyo.png"), to: { name: "yoyoCoinIntroduce" }, w: 10 },
            { name: "cart", icon: require("@/assets/images/tabbar/cart-active.png"), to: { name: "cart", query: { showTabbar: true } }, w: 8 },
            { name: "mine", icon: require("@/assets/images/tabbar/my.png"), to: { name: "mine" }, w: 10 },
          ]
        : [
            { name: "home", icon: require("@/assets/images/tabbar/home-en.png"), to: { name: "home" }, w: 8 },
            { name: "yoyoCoinIntroduce", icon: require("@/assets/images/tabbar/yoyo-en.png"), to: { name: "yoyoCoinIntroduce" }, w: 10 },
            { name: "cart", icon: require("@/assets/images/tabbar/cart-en-active.png"), to: { name: "cart", query: { showTabbar: true } }, w: 8 },
            { name: "mine", icon: require("@/assets/images/tabbar/my-en.png"), to: { name: "mine" }, w: 10 },
          ]
    },
    totalAmount() {
      return this.cartItems.reduce((total, item) => total + item.price * item.quantity, 0)
    },
    ...mapGetters({
      isZh: "lang/isZh",
      isLoggedIn: "auth/isLoggedIn",
    }),
  },
  mounted() {
    // this.loadCartData()
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    loadCartData() {
      // 从localStorage加载购物车数据
      const cartData = localStorage.getItem("yoyotravel_cart")
      if (cartData) {
        this.cartItems = JSON.parse(cartData)
        console.log("this.cartItems :>> ", this.cartItems)
      }
    },
    saveCartData() {
      // 保存购物车数据到localStorage
      localStorage.setItem("yoyotravel_cart", JSON.stringify(this.cartItems))
    },
    increaseQuantity(item) {
      if (!this.isMaxQuantityReached(item)) {
        item.quantity++
        this.saveCartData()
      }
    },
    handleDecrease(item) {
      if (item.quantity === 1) {
        // 数量为1时，删除商品
        this.removeItem(item.id)
      } else {
        // 数量大于1时，减少数量
        item.quantity--
        this.saveCartData()
      }
    },
    isMaxQuantityReached(item) {
      return item.quantity >= item.maxQuantity
    },
    removeItem(itemId) {
      this.cartItems = this.cartItems.filter((item) => item.id !== itemId)
      this.saveCartData()
    },
    goShopping() {
      this.$router.push("/")
    },
    checkout() {
      if (this.totalCount === 0) {
        this.$toast("购物车为空")
        return
      }
      
      const cartData = localStorage.getItem("yoyotravel_cart")
      localStorage.setItem("yoyotravel_settleData", cartData)

      // 结算逻辑
      this.$router.push("/pay")
    },
    // 处理滚动事件 - 结合两者优点的混合逻辑
    handleScroll() {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop
      const windowHeight = window.innerHeight
      const documentHeight = document.documentElement.scrollHeight

      // 1. 立即更新 HomeHeader 的滚动进度（实时响应，无防抖）
      this.updateHeaderScrollProgress(scrollTop)

      // 2. 立即更新 Tabbar 显示逻辑（实时响应，无防抖）
      this.updateTabbarVisibility(scrollTop, windowHeight, documentHeight)
    },

    // HomeHeader 滚动进度更新（防抖动优化版本）
    updateHeaderScrollProgress(scrollTop) {
      // 1. 计算scrollTop变化量
      const scrollDiff = Math.abs(scrollTop - this.lastHeaderScrollTop)

      // 2. 设置阈值：只有滚动距离超过3px才更新
      const scrollThreshold = 3

      // console.log(
      //   "🎯 [滚动检测] scrollTop:",
      //   scrollTop.toFixed(2),
      //   "上次:",
      //   this.lastHeaderScrollTop.toFixed(2),
      //   "差值:",
      //   scrollDiff.toFixed(2),
      //   "px",
      // )

      // 3. 如果变化量小于阈值，直接跳过
      if (scrollDiff < scrollThreshold) {
        // console.log("⏸️ [跳过更新] 变化太小 (<", scrollThreshold, "px)")
        return
      }

      // 4. 计算新的进度值
      const rawProgress = Math.min(scrollTop / this.maxScrollForHeaderAnimation, 1)

      // 5. 四舍五入到小数点后2位，进一步减少微小变化
      const roundedProgress = Math.round(rawProgress * 100) / 100

      // 6. 检查进度是否真的变化了
      if (Math.abs(roundedProgress - this.scrollProgress) < 0.01) {
        // console.log("⏸️ [跳过更新] 进度值未变化，当前:", this.scrollProgress)
        // 即使进度没变，也更新lastHeaderScrollTop，避免累积效应
        this.lastHeaderScrollTop = scrollTop
        return
      }

      // 7. 更新进度和记录位置
      // console.log("✅ [更新进度]", this.scrollProgress.toFixed(3), "→", roundedProgress.toFixed(3), "| scrollTop:", scrollTop.toFixed(2))
      this.scrollProgress = roundedProgress
      this.lastHeaderScrollTop = scrollTop
    },

    // Tabbar 显示逻辑（来自 Home.vue 的简单逻辑）
    updateTabbarVisibility(scrollTop, windowHeight, documentHeight) {
      // 判断是否滚动到页面底部（距离底部50px内）
      const isNearBottom = scrollTop + windowHeight >= documentHeight - 1

      // 如果在页面底部，显示tabbar
      if (isNearBottom) {
        this.showTabbar = true
        this.lastScrollTop = scrollTop
        return
      }

      // 判断滚动方向
      const scrollDirection = scrollTop > this.lastScrollTop ? "down" : "up"

      // 只有滚动距离超过阈值才触发显示/隐藏
      if (Math.abs(scrollTop - this.lastScrollTop) > this.scrollThreshold) {
        if (scrollDirection === "down") {
          // 向下滚动，隐藏tabbar
          this.showTabbar = false
        } else {
          // 向上滚动，显示tabbar
          this.showTabbar = true
        }
        this.lastScrollTop = scrollTop
      }
    },
  },
  created() {
    // 添加滚动事件监听
    window.addEventListener("scroll", this.handleScroll, { passive: true })
    this.loadCartData()
    console.log("this.$route.params :>> ", this.$route)
  },
}
</script>

<style scoped>
.cart-page {
}

/deep/.van-tabbar-item__icon img {
  height: auto;
}
</style>
